package com.hty.PowerChat;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pclientbackend.ChatClient;
import pclientbackend.IdArray;
import pclientbackend.MsgType;
import pclientbackend.Pclientbackend;
import pclientbackend.UserDataArray;
import pclientbackend.UserDataRet;

public class MainActivity extends AppCompatActivity {

    ImageButton imageButton_avatar, imageButton_add, imageButton_WEB;
    TextView textView_title;
    LinearLayout layout_dynamic;
    ListView listView_stranger, listView_contact, listView_function;
    List<Integer> list_function_image = new ArrayList<>();
    List<String> list_function_name = new ArrayList<>();
    SimpleAdapter adapter_stranger, adapter_contact, adapter_function;
    List<HashMap<String,Object>> list_contact = new ArrayList<>();
    List<HashMap<String,Object>> list_stranger = new ArrayList<>();
    List<HashMap<String,Object>> list_function_items = new ArrayList<>();
    String uid="", uname = "", usex = "女", uage="", udesc="";
    ChatClient chatClient;
    boolean exitMsgThread = false, exitUserStatusThread = false;
    SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_chat:
                    textView_title.setText("聊天");
                    listView_stranger.setVisibility(View.VISIBLE);
                    listView_contact.setVisibility(View.GONE);
                    layout_dynamic.setVisibility(View.GONE);
                    return true;
                case R.id.navigation_contact:
                    textView_title.setText("联系人");
                    listView_stranger.setVisibility(View.GONE);
                    listView_contact.setVisibility(View.VISIBLE);
                    layout_dynamic.setVisibility(View.GONE);
                    return true;
                case R.id.navigation_dynamic:
                    textView_title.setText("动态");
                    listView_stranger.setVisibility(View.GONE);
                    listView_contact.setVisibility(View.GONE);
                    layout_dynamic.setVisibility(View.VISIBLE);
                    return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //使用自定义布局
        actionBar.setCustomView(R.layout.actionbar_main);

        imageButton_avatar = findViewById(R.id.imageButton_avatar);
        imageButton_add = findViewById(R.id.imageButton_add);
        imageButton_WEB = findViewById(R.id.imageButton_WEB);
        imageButton_avatar.setOnClickListener(new ClickListener());
        imageButton_add.setOnClickListener(new ClickListener());
        imageButton_WEB.setOnClickListener(new ClickListener());
        textView_title = findViewById(R.id.textView_title);
        textView_title.setText("聊天");
        listView_stranger = findViewById(R.id.listView_stranger);
        listView_contact = findViewById(R.id.listView_contact);
        listView_contact.setVisibility(View.GONE);

        BottomNavigationView navigation = findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        Intent intent = getIntent();
        HashMap map = (HashMap) intent.getSerializableExtra("user");
        uname = map.get("name").toString();
        uid = map.get("id").toString();
        long sex = (long) map.get("sex");
        if(sex == 1){
            usex = "男";
        }
        uage = map.get("age").toString();
        udesc = map.get("desc").toString();

        // 好友列表
        adapter_contact = new SimpleAdapter(MainActivity.this, list_contact, R.layout.list_contact_item, new String[]{"id", "avatar", "name" }, new int[]{ R.id.textView_id,  R.id.imageView_avatar, R.id.textView_name });
        adapter_contact.setViewBinder(new SimpleAdapter.ViewBinder(){
            long userStatus;
            public boolean setViewValue(View view, Object data, String textRepresentation){
                if (view.getId() == R.id.textView_id) {
                    String id = (String)data;
                    for(int i=0; i<list_contact.size(); i++) {
                        if(list_contact.get(i).get("id").equals(id)) {
                            userStatus = (Long)list_contact.get(i).get("userStatus");
                            //Log.e(Thread.currentThread().getStackTrace()[2] + "", id + " , " + userStatus);
                            break;
                        }
                    }
                }
                if(view.getId() == R.id.imageView_avatar){
                    ((ImageView)view).setImageResource((int)data);
                    if(userStatus == 0){    //offline
                        ColorMatrix CM = new ColorMatrix();
                        CM.setSaturation(0); // 设置饱和度
                        ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(CM);
                        ((ImageView)view).setColorFilter(colorFilter);
                    }else{
                        ((ImageView)view).setColorFilter(null); //清空
                    }
                    return true;
                }
                return false;
            }
        });
        listView_contact.setAdapter(adapter_contact);

        listView_contact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, final View view, int position, long id) {
                String sid = ((TextView) view.findViewById(R.id.textView_id)).getText().toString();
                for(int i=0; i<list_contact.size(); i++) {
                    if(list_contact.get(i).get("id").equals(sid)) {
                        Intent intent = new Intent(MainActivity.this, ChatActivity.class);
                        intent.putExtra("contact", list_contact.get(i));
                        startActivity(intent);
                        break;
                    }
                }
            }
        });

        listView_contact.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
                final String cid = ((TextView) view.findViewById(R.id.textView_id)).getText().toString();
                for(int i=0; i<list_contact.size(); i++) {
                    if(list_contact.get(i).get("id").equals(cid)) {
                        String sex = list_contact.get(i).get("sex").toString()=="1"?"男":"女";
                        String s = "Id：\t" + cid + "\n用户名：\t" + list_contact.get(i).get("name") + "\n" + "性别：\t" + sex + "\n" + "年龄：\t" + list_contact.get(i).get("age") + "\n签名：\t" + list_contact.get(i).get("desc");
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
                                .setIcon(android.R.drawable.stat_sys_warning)
                                .setTitle("删除")
                                .setMessage(s)
                                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        chatClient.removeFriend(Long.parseLong(cid));
                                        dialog.dismiss();
                                        getFriends();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        AlertDialog dialog = builder.create();
                        dialog.show();
                        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.RED);
                        try {
                            //获取Dialog对象
                            Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
                            mAlert.setAccessible(true);
                            Object mAlertController = mAlert.get(dialog);
                            //获取Title并设置
                            Field mTitle = mAlertController.getClass().getDeclaredField("mTitleView");
                            mTitle.setAccessible(true);
                            TextView mTitleView = (TextView) mTitle.get(mAlertController);
                            mTitleView.setTextColor(Color.RED);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (NoSuchFieldException e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                }
                return true;    //屏蔽ItemClick
            }
        });

        // 陌生人列表
        adapter_stranger = new SimpleAdapter(MainActivity.this, list_stranger, R.layout.list_contact_item, new String[]{"id", "avatar", "name" }, new int[]{ R.id.textView_id,  R.id.imageView_avatar, R.id.textView_name });
        adapter_stranger.setViewBinder(new SimpleAdapter.ViewBinder(){
            long userStatus;
            public boolean setViewValue(View view, Object data, String textRepresentation){
                if (view.getId() == R.id.textView_id) {
                    String id = (String)data;
                    for(int i=0; i<list_stranger.size(); i++) {
                        if(list_stranger.get(i).get("id").equals(id)) {
                            userStatus = (Long)list_stranger.get(i).get("userStatus");
                            //Log.e(Thread.currentThread().getStackTrace()[2] + "", id + " , " + userStatus);
                            break;
                        }
                    }
                }
                if(view.getId() == R.id.imageView_avatar){
                    ((ImageView)view).setImageResource((int)data);
                    if(userStatus == 0){    //offline
                        ColorMatrix CM = new ColorMatrix();
                        CM.setSaturation(0); // 设置饱和度
                        ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(CM);
                        ((ImageView)view).setColorFilter(colorFilter);
                    }else{
                        ((ImageView)view).setColorFilter(null); //清空
                    }
                    return true;
                }
                return false;
            }
        });
        listView_stranger.setAdapter(adapter_stranger);

        listView_stranger.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, final View view, int position, long id) {
                String sid = ((TextView) view.findViewById(R.id.textView_id)).getText().toString();
                for(int i=0; i<list_stranger.size(); i++) {
                    if(list_stranger.get(i).get("id").equals(sid)) {
                        Intent intent = new Intent(MainActivity.this, ChatActivity.class);
                        intent.putExtra("contact", list_stranger.get(i));
                        startActivity(intent);
                        break;
                    }
                }
            }
        });

        listView_stranger.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
                final String sid = ((TextView) view.findViewById(R.id.textView_id)).getText().toString();
                for (int i=0; i<list_stranger.size(); i++) {
                    if (list_stranger.get(i).get("id").equals(sid)) {
                        String sex = list_stranger.get(i).get("sex").toString()=="1"?"男":"女";
                        String s = "Id：\t" + sid + "\n用户名：\t" + list_stranger.get(i).get("name") + "\n" + "性别：\t" + sex + "\n" + "年龄：\t" + list_stranger.get(i).get("age") + "\n签名：\t" + list_stranger.get(i).get("desc");
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
                                .setIcon(R.mipmap.avatar)
                                .setTitle("陌生人")
                                .setMessage(s)
                                .setPositiveButton("添加", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        chatClient.addFriend(Long.parseLong(sid));
                                        dialog.dismiss();
                                        getFriends();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        AlertDialog dialog = builder.create();
                        dialog.show();
                        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLUE);
                        break;
                    }
                }
                return true;    //屏蔽ItemClick
            }
        });

        layout_dynamic = findViewById(R.id.layout_dynamic);
        layout_dynamic.setVisibility(View.GONE);

        listView_function = findViewById(R.id.listView_function);

        list_function_name.add("音乐");
        list_function_name.add("荔枝FM");
        list_function_name.add("腾讯新闻");
        list_function_name.add("关于");
        list_function_name.add("退出");

        list_function_image.add(R.mipmap.qqmusic);
        list_function_image.add(R.mipmap.lizhifm);
        list_function_image.add(R.mipmap.qq);
        list_function_image.add(R.mipmap.about);
        list_function_image.add(R.drawable.ic_exit_to_app_black_48dp);

        for(int i=0; i<list_function_name.size(); i++){
            HashMap<String, Object> listItem = new HashMap<>();
            listItem.put("image", list_function_image.get(i));
            listItem.put("name", list_function_name.get(i));
            list_function_items.add(listItem);
        }
        adapter_function = new SimpleAdapter(MainActivity.this, list_function_items, R.layout.list_function_item, new String[]{"image", "name"}, new int[]{ R.id.imageView_function, R.id.textView_function });
        listView_function.setAdapter(adapter_function);
        adapter_function.notifyDataSetChanged();

        listView_function.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, final View view, int position, long id) {
                switch (position){
                    case 0:
                        Intent intent = new Intent(MainActivity.this, BrowserActivity.class);
                        intent.putExtra("url", "http://y.qq.com");
                        startActivity(intent);
                        break;
                    case 1:
                        intent = new Intent(MainActivity.this, BrowserActivity.class);
                        intent.putExtra("url", "http://lizhi.fm");
                        startActivity(intent);
                        break;
                    case 2:
                        intent = new Intent(MainActivity.this, BrowserActivity.class);
                        intent.putExtra("url", "http://www.qq.com");
                        startActivity(intent);
                        break;
                    case 3:
                        new AlertDialog.Builder(MainActivity.this).setIcon(R.mipmap.ic_launcher).setTitle("PowerChat 1.3 alpha").setMessage("海天鹰聊天界面的PowerChat安卓客户端。\n作者：海天鹰\nAndroid版：https://gitee.com/sonichy/PowerChat_Android\nWindows版和Linux版：\nhttps://gitee.com/rocket049/powerchat").setPositiveButton("确定", null).show();
                        break;
                    case 4:
                        exitMsgThread = true;
                        exitUserStatusThread = true;
                        finish();
                        break;
                }
            }
        });

        getFriends();
        //getStranger();
        MsgThread msgThread = new MsgThread();
        msgThread.start();
        UserStatusThread userStatusThread = new UserStatusThread();
        userStatusThread.start();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        boolean isAdded = data.getExtras().getBoolean("isAdded");
        Log.e(Thread.currentThread().getStackTrace()[2] + "", String.valueOf(isAdded));
        if (isAdded) getFriends();
    }

    class ClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.imageButton_avatar:
                    String s = "Id：\t" + uid + "\n用户名：\t" + uname + "\n" + "性别：\t" + usex + "\n" + "年龄：\t" + uage + "\n签名：\t" + udesc;
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
                            .setIcon(R.mipmap.logo)
                            .setTitle("信息")
                            .setMessage(s)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setNeutralButton("修改密码", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(MainActivity.this, ModifyPasswordActivity.class);
                                    intent.putExtra("uname", uname);
                                    startActivity(intent);
                                }
                            })
                            .setNegativeButton("修改签名", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    final EditText editText_desc = new EditText(MainActivity.this);
                                    editText_desc.setText(udesc);
                                    editText_desc.setSelection(editText_desc.length());
                                    AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this)
                                            .setTitle("修改签名")
                                            .setIcon(android.R.drawable.ic_menu_edit)
                                            .setView(editText_desc)
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    String s = editText_desc.getText().toString();
                                                    if(!s.equals("")){
                                                        udesc = s;
                                                        chatClient.updateDesc(s);
                                                    }
                                                }
                                            })
                                            .setNegativeButton("取消", null);
                                    AlertDialog dialog1 = builder1.create();
                                    dialog1.show();
                                    dialog1.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLUE);
                                }
                            });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLUE);
                    dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(Color.BLUE);
                    break;
                case R.id.imageButton_add:
                    Intent intent = new Intent(MainActivity.this, AddActivity.class);
                    startActivityForResult(intent, 1);
                    break;
                case R.id.imageButton_WEB:
                    chatClient.setServeId(Long.parseLong(uid));
                    String url = chatClient.getUrl();
                    Log.e(Thread.currentThread().getStackTrace()[2] + "", url);
                    intent = new Intent(MainActivity.this, BrowserActivity.class);
                    intent.putExtra("url", url);
                    startActivity(intent);
                    break;
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what){
                case 0:
                    String message = msg.obj.toString();
                    //Toast.makeText(MainActivity.this, msg.arg1 + " -> " + message + " -> " + msg.arg2, Toast.LENGTH_SHORT).show();
                    if (message.equals("LOGI")) {//登录消息
                        for (int i = 0; i < list_contact.size(); i++) {
                            if(Integer.parseInt(list_contact.get(i).get("id").toString()) == msg.arg1) {
                                long us = 1;
                                list_contact.get(i).put("userStatus", us);
                                Collections.sort(list_contact, new UserStatusComparetor());
                                adapter_contact.notifyDataSetChanged();
                                break;
                            }
                        }
                    } else if (message.startsWith("Offline ") && msg.arg1 == 0 && msg.arg2 == 0) {//离线消息
                        String id = message.substring(8);
                        Log.e(Thread.currentThread().getStackTrace()[2] + "", "Offline " + id);
                        for (int i = 0; i < list_contact.size(); i++) {
                            if(list_contact.get(i).get("id").toString().equals(id)) {
                                long us = 0;
                                list_contact.get(i).put("userStatus", us);
                                Collections.sort(list_contact, new UserStatusComparetor());
                                adapter_contact.notifyDataSetChanged();
                                break;
                            }
                        }
                    }
                    //添加陌生人消息到列表
                    boolean isStranger = true;
                    for (int i = 0; i < list_contact.size(); i++) {
                        Log.e(Thread.currentThread().getStackTrace()[2] + "", list_contact.get(i).get("id").toString() + " = " + msg.arg1);
                        if (Integer.parseInt(list_contact.get(i).get("id").toString()) == msg.arg1) {//消息来自联系人
                            isStranger = false;
                            break;
                        }
                    }
                    if (isStranger) {//消息来自陌生人
                        boolean isInStrangerList = false;
                        for (int j=0; j < list_stranger.size(); j++) {
                            if (Integer.parseInt(list_stranger.get(j).get("id").toString()) == msg.arg1) {//陌生人已在陌生人列表中
                                isInStrangerList = true;
                                break;
                            }
                        }
                        if (!isInStrangerList) {
                            UserDataRet userDataRet = chatClient.queryID(msg.arg1, "");
                            HashMap<String, Object> listItem = new HashMap<>();
                            listItem.put("id", Integer.toString(msg.arg1));
                            listItem.put("avatar", R.mipmap.avatar);
                            listItem.put("name", userDataRet.getName());
                            //long sex = 1;
                            listItem.put("sex", userDataRet.getSex());
                            //long age = 1;
                            listItem.put("age", userDataRet.getAge());
                            listItem.put("desc", userDataRet.getDesc());
                            long us = 1;
                            listItem.put("userStatus", us);
                            list_stranger.add(listItem);
                            adapter_stranger.notifyDataSetChanged();
                        }
                    }
                    break;
                case 1:
                    Log.e(Thread.currentThread().getStackTrace()[2] + "", "update userStatus");
                    adapter_contact.notifyDataSetChanged();
                    break;
            }

        };
    };

    class MsgThread extends Thread{
        public void run(){
            while(!exitMsgThread){
                String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "PowerChat";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                String json = "{\"Host\":\"148.70.58.15:7889\"}";
                chatClient = Pclientbackend.getChatClient(path, json);
                MsgType msgType = chatClient.getMsg();
                String msg = new String(msgType.getMsg());
                long from = msgType.getFrom();
                long to = msgType.getTo();
                Log.e(Thread.currentThread().getStackTrace()[2] + "", from + " -> " + msg + " -> " + to);
                Message message = Message.obtain();
                message.what = 0;
                message.arg1 = (int)from;
                message.arg2 = (int)to;
                message.obj = msg;
                handler.sendMessage(message);
                if(!msg.equals("") && !msg.equals("LOGI") && !(from == 0 && to == 0)) {
                    DBHelper DBH = new DBHelper(getApplicationContext());   //报错
                    //DBHelper DBH = DBHelper.getInstance(getApplicationContext()); //attempt to re-open an already-closed object: SQLiteDatabase 崩溃
                    ContentValues values = new ContentValues();
                    values.put("message", msg);
                    values.put("mfrom", msgType.getFrom());
                    values.put("mto", msgType.getTo());
                    Date time = new Date();
                    values.put("time", timeformat.format(time));
                    DBH.insert("chat" + uid, values);
                    DBH.close();
                    //好奇怪啊，无消息自动睡眠，不需要自定义打盹
                    //try {
                    //    Thread.sleep(1000);
                    //} catch (Exception e) {
                    //    e.printStackTrace();
                    //}
                }
            }
            //chatClient.quit(); // 退出chatClient后，Pclientbackend.getChatClient()==null 再次登录崩溃
        }
    }

    class UserStatusThread extends Thread{
        public void run(){
            while(!exitUserStatusThread){
                String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "HTYChat";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                String json = "{\"Host\":\"148.70.58.15:7889\"}";
                chatClient = Pclientbackend.getChatClient(path, json);
                for(int i=0; i<list_contact.size(); i++) {
                    long id = Long.parseLong(list_contact.get(i).get("id").toString());
                    long userStatus = chatClient.userStatus(id);
                    list_contact.get(i).put("userStatus", userStatus);
                }
                Collections.sort(list_contact, new UserStatusComparetor());
                for(int i=0; i<list_stranger.size(); i++) {
                    long id = Long.parseLong(list_stranger.get(i).get("id").toString());
                    long userStatus = chatClient.userStatus(id);
                    list_stranger.get(i).put("userStatus", userStatus);
                }
                Collections.sort(list_stranger, new UserStatusComparetor());
                Message message = Message.obtain();
                message.what = 1;
                handler.sendMessage(message);
                try {
                    Thread.sleep(60000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class UserStatusComparetor implements Comparator<Map<String, Object>> {
        @Override
        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            long d = (Long)o2.get("userStatus") - (Long)o1.get("userStatus");
            if(d > 0){
                return 1;
            }else if(d == 0){
                return 0;
            }else{
                return -1;
            }
        }
    }

    void getFriends() {
        list_contact.clear();
        String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "HTYChat";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String json = "{\"Host\":\"148.70.58.15:7889\"}";
        chatClient = Pclientbackend.getChatClient(path, json);
        UserDataArray userDataArray = chatClient.getFriends();
        UserDataRet userDataRet;
        IdArray idArray = new IdArray();
        while((userDataRet = userDataArray.next()) != null){
            idArray.append(userDataRet.getId());
            HashMap<String, Object> listItem = new HashMap<>();
            listItem.put("id", Long.toString(userDataRet.getId()));
            listItem.put("name", userDataRet.getName());
            listItem.put("sex", userDataRet.getSex());
            listItem.put("age", userDataRet.getAge());
            listItem.put("desc", userDataRet.getDesc());
            listItem.put("avatar", R.mipmap.avatar);
            long us = 1;
            listItem.put("userStatus", us);
            list_contact.add(listItem);
        }
        chatClient.tellAll(idArray);
        adapter_contact.notifyDataSetChanged();
    }

    void getStranger() {
        list_stranger.clear();
        String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "HTYChat";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String json = "{\"Host\":\"148.70.58.15:7889\"}";
        chatClient = Pclientbackend.getChatClient(path, json);
        UserDataArray userDataArray = chatClient.getStrangerMsgs();
        Log.e(Thread.currentThread().getStackTrace()[2] + "", userDataArray.toString());
        UserDataRet userDataRet;
        IdArray idArray = new IdArray();
        while((userDataRet = userDataArray.next()) != null){
            Log.e(Thread.currentThread().getStackTrace()[2] + "", userDataRet.toString());
            idArray.append(userDataRet.getId());
            HashMap<String, Object> listItem = new HashMap<>();
            listItem.put("id", Long.toString(userDataRet.getId()));
            listItem.put("name", userDataRet.getName());
            listItem.put("sex", userDataRet.getSex());
            listItem.put("age", userDataRet.getAge());
            listItem.put("desc", userDataRet.getDesc());
            listItem.put("avatar", R.mipmap.avatar);
            long us = 1;
            listItem.put("userStatus", us);
            list_stranger.add(listItem);
        }
        chatClient.tellAll(idArray);
        adapter_stranger.notifyDataSetChanged();
    }

}